function rem(designWidth, maxWidth) {
	var doc = document,
		win = window,
		docEl = doc.documentElement,
		remStyle = document.createElement("style"),
		tid;

	function refreshRem() {
		var width = docEl.getBoundingClientRect().width;
		maxWidth = maxWidth || 540;
		width > maxWidth && (width = maxWidth);
		var rem = width * 100 / designWidth;
		remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';
	}

	if (docEl.firstElementChild) {
		docEl.firstElementChild.appendChild(remStyle);
	} else {
		var wrap = doc.createElement("div");
		wrap.appendChild(remStyle);
		doc.write(wrap.innerHTML);
		wrap = null;
	}
	refreshRem();

	win.addEventListener("resize", function () {
		clearTimeout(tid);
		tid = setTimeout(refreshRem, 300);
	}, false);

	win.addEventListener("pageshow", function (e) {
		if (e.persisted) {
			clearTimeout(tid);
			tid = setTimeout(refreshRem, 300);
		}
	}, false);

	if (doc.readyState === "complete") {
		doc.body.style.fontSize = "16px";
	} else {
		doc.addEventListener("DOMContentLoaded", function (e) {
			doc.body.style.fontSize = "16px";
		}, false);
	}
	document.addEventListener('DOMContentLoaded', function () {
		FastClick.attach(document.body);
	}, false);
}
rem(750, 1024);

//项目部分
var api_init;
var baseUrl = "http://gongren.xiaoyingwu.cn/api"  //接口地址 http://gongren.xiaoyingwu.cn/api.php
var sokectUrl = 'ws://www.marketcar.cn:6300/ws' //sokect地址
apiready = function () { 
	initIceFox(false);
}
initIceFox(true);
function initIceFox(isPc) {
	Vue.use(iceFox) //加载 冰狐 插件
	if (!isPc) { 
		Vue ? Vue.prototype.$env = (api.debug ? 'dev' : 'pro') : ''; //开发环境 dev 生产环境 pro  
		/* 设置frame背景*/
		api.setStatusBarStyle({ 
			style: 'dark',
		});
		api.setWinAttr({
			bgColor: "#F8F9FB",
		});
		api_init() //初始化Vue
		immersive();
		/**
		 * 页面公用跳转
		 * @param:添加节点class link-page
		 * @param:data-id 接收：api.pageParam.id;
		*/
		(function () {
			var linkPage = document.querySelectorAll('.link-page');
			for (var i = 0; i < linkPage.length; i++) {
				linkPage[i].addEventListener('click', function () {
					var paramString = this.dataset;
					var obj = {
						url: '',
						pageParam: {},
					};
					for (var key in paramString) {
						if (paramString.hasOwnProperty(key)) {
							key == "url" ? obj.url = paramString[key] : obj.pageParam[key] = paramString[key];
						}
					}
					api.openWin({
						name: obj.url,
						url: obj.url,
						pageParam: obj.pageParam,
					})
				}, false)
			}
		})();
		/**
		 * 公用返回
		 * @param:添加公用类:back
		*/
		(function () {
			var backPage = document.querySelectorAll('.back');
			for (var i = 0; i < backPage.length; i++) {
				backPage[i].addEventListener('click', function () {
					api.closeWin();
				}, true)
			}
		})();
	} else {
		setTimeout(function () {
			api_init();
		}, 700)
	}
}
// 沉浸式
function immersive() {
	if (api.statusBarAppearance) {
		var safeArea = api.safeArea.top;
		var safeArea_bottom = api.safeArea.bottom;
		var header = document.querySelector('.header');
		var main = document.querySelector('.main');
		var footer = document.querySelector('.footer')
		if (header != null) {
			var headerHeight = header.clientHeight;
			header.style.height = headerHeight + safeArea + "px";
			header.style.paddingTop = safeArea + "px";
		}
		if (main != null) {
			if (header) {
				var headerHeight = header.clientHeight;
				main.style.paddingTop = headerHeight + "px";
			} else {
				main.style.paddingTop = safeArea + "px";
			}
		}
		if (footer != null) {
			var height2 = footer.clientHeight;
			footer.style.height = height2 + safeArea_bottom + "px";
			footer.style.paddingBottom = safeArea_bottom + "px";
		}
	}
}
//下拉加载
function btLoad(_this, methods) {
	var fn = methods || "getList";
	// 上拉加载
	var timp = "";
	api.addEventListener({
		name: 'scrolltobottom',
		extra: { threshold: 20 }
	}, function (ret, err) {
		//上拉加载时需要加载的数据
		if (_this.list.length == _this.total) {
			return false
		} else {
			clearTimeout(timp)
			timp = setTimeout(function () {
				_this[fn]();
			}, 300)
		}
	});
}
//判断是否登录
function isLogin() {
	return fox.storage.get('userToken') != '';
}
//判断是否是IOS
function isIos() {
	var systemType = api.systemType;
	return systemType == "ios";
}
//根据两个时间戳计算相差小时和天数（）@param1：当前时间 @param2：结束时间
function interval(faultDate, completeTime) {
	var usedTime = completeTime - faultDate;  //两个时间戳相差的毫秒数
	if (usedTime < 0) {
		return {
			m: 0,
			s: 0,
		}
	}
	var m = Math.floor(usedTime % (60 * 60) / 60);
	var s = Math.floor(usedTime % (60 * 60) % 60);
	if (m < 10) {
		m = "0" + m
	}
	if (s < 10) {
		s = "0" + s
	}
	return {
		m: m,
		s: s,
	}
}
function intervalMin(usedTime) {
	usedTime = usedTime;
	var m = Math.floor(usedTime / 60);
	var s = Math.floor(usedTime % 60);
	if (m < 10) {
		m = "0" + m
	}
	if (s < 10) {
		s = "0" + s
	}
	return {
		m: m,
		s: s,
	}
}

function ExitApp() {
	var ci = 0;
	var time1, time2;
	api.addEventListener({
		name: 'keyback'
	}, function (ret, err) {
		if (ci == 0) {
			time1 = new Date().getTime();
			ci = 1;
			api.toast({ msg: '再按一次返回键退出' });
		} else if (ci == 1) {
			time2 = new Date().getTime();
			if (time2 - time1 < 3000) {
				api.closeWidget({
					id: api.appId,
					retData: {
						name: 'closeWidget'
					},
					silent: true
				});
			} else {
				ci = 0;
				api.toast({ msg: '再按一次返回键退出' });
			}
		}
	});
}
/*swiper*/
function swiper(domStr) {
	var domStr = domStr || '.swiper-container';
	var swiper = new Swiper(domStr, {
		loop: true,
		pagination: {
			el: '.swiper-pagination',
		},
		autoplay: {
			delay: 3000,
			disableOnInteraction: false,
		},
		on: {
			touchStart: function (event) {
				api.setFrameAttr({
					name: api.frameName,
					bounces: false
				});
			},
			touchEnd: function (event) {
				api.setFrameAttr({
					name: api.frameName,
					bounces: true
				});
			},
		}
	});
}
/**
 *  1课程
    2科目
    3外链
    4无连接
*/
function swiperLinkEvent(targetItem){
	if(!isLogin()){
		fox.navigateTo({url:"widget://html/login"})
		return false
	}
	if(!targetItem || !targetItem.type)return
	switch(Number(targetItem.type.id)){
		case 1:
          fox.navigateTo({url:"../shop/car_detail?id="+targetItem.item})
		break;
		case 2:
          fox.navigateTo({url:"../shop/coop_detail?id="+targetItem.item})
		break;
		case 3:
			api.openWin({
				name:"h5page",
				url:"widget://html/libs/h5page.html",
				pageParam:{
					url:targetItem.item
				}
			})
		break;
	}
}
// 数组过滤空值
function filterAll(arr) {
	var target = arr.filter(function (current) {
		return current !== null && current !== undefined && current !== "";
	})
	target = target.map(function (v) {
		v.goods = [];
		return v
	})
	return target;
}
//数尾补两个0 1=>1.00 , 2.2=>2.20;
function setNum2(num) {
	num += '';
	num = num.replace(/[^0-9|\.]/g, '');
	if (/^0+/) { num = num.replace(/^0+/, '') }
	if (!/\./.test(num)) { num += '.00' }
	if (/^\./.test(num)) { num = '0' + num }
	num += '00';
	num = num.match(/\d+\.\d{2}/)[0];
	return num
}
//打电话
function callPhone(phone) {
	fox.showModal({
		title: "拨打电话",
		content: "确定呼叫 " + phone + " 吗?",
		icon: "widget://res/call.png",
		rightBtn: "呼叫",
		success: function (res) {
			if (res.confirm) {
				api.call({
					type: 'tel_prompt',
					number: phone,
				});
			}
		}
	})
}

/*计算缓存*/
function computedCash(size) {
	var size = ~~(size / 1024); //kb
	if (size > 1024) {
		size = ~~(size / 1024) + "MB";
	} else {
		size = size + "KB";
	}
	return size;
}
//选择图片
function chosePic(callback) {
	function getPic(t, callback) {
		api.getPicture({
			sourceType: t,
			encodingType: 'jpg',
			mediaValue: 'pic',
			destinationType: 'url',
			allowEdit: true,
			quality: 30,
		}, function (ret, err) {
			if (ret) {
				if (ret.data != "") {
					data = ret.data;
					callback(data)
				}
			} else {
				api.toast({
					msg: '请重试'
				});
			}
		});
	}
	api.actionSheet({
		cancelTitle: '取消',
		buttons: ['拍照', '从相册选择'],
		style: {
			fontNormalColor: '#000',
		}
	}, function (ret, err) {
		var index = ret.buttonIndex;
		if (index == 1) {
			getPic('camera', callback);
		} else if (index == 2) {
			getPic('photos', callback);
		}
	});
}
//普通时间戳处理
function dateFormat(timestamp, formats) {
	// formats格式包括
	// 1. Y-m-d
	// 2. Y-m-d H:i:s
	// 3. Y年m月d日
	// 4. Y年m月d日 H时i分
	formats = formats || 'Y-m-d';
	var zero = function (value) {
		if (value < 10) {
			return '0' + value;
		}
		return value;
	};
	var myDate = timestamp ? new Date(timestamp) : new Date();
	var year = myDate.getFullYear();
	var month = zero(myDate.getMonth() + 1);
	var day = zero(myDate.getDate());
	var hour = zero(myDate.getHours());
	var minite = zero(myDate.getMinutes());
	var second = zero(myDate.getSeconds());
	return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
		return ({
			Y: year,
			m: month,
			d: day,
			H: hour,
			i: minite,
			s: second
		})[matches];
	});
};
/**
 * 2020-8-18 新增权限，以前权限代码是坨屎，乱动容易脏手，
*/
//权限检测并获取
function checkhasPermission(permissionArr,callBack){
	var resultList = api.hasPermission({
		list:permissionArr,
	});
	//判断用户没有哪个权限
	var noPermission = resultList.filter(function(v){
		return v.granted ? "" :v
	})
	if (noPermission.length != 0) {
		getPermission(noPermission,callBack);
	}else{
		callBack();
	}
}
//申请权限
function getPermission(perList,callBack){
	if (perList.length == 0) {
		return false
	}
	var perName = perList.map(function(v){return v.name});
	api.confirm({
		title: '提示',
		msg: '检测到您有'+translatePermission(perName[0])+'权限未开启是否前往授权',
		buttons:['确定', '取消']
	},function(ret,err){
		if(ret.buttonIndex == 1){
			api.requestPermission({
				list:perName,
				code:1
			}, function(ret, err){
				var noPermission = ret.list.filter(function(v){return v.granted && !v.never ? "" : v})
				if(noPermission.length == 0){
					callBack();
				}else{
					getPermission(noPermission,callBack)
				}
			});
		}
	});
}
//权限翻译，把对应英文转换成中文
function translatePermission(name){
	var arr = [
		{name:"location",chinese:"定位"},
		{name:"locationAlways",chinese:"持续定位"},
		{name:"notification",chinese:"通知"},
		{name:"phone-call",chinese:"电话"},
		{name:"storage",chinese:"存储"},
	]
	return arr.filter(function(v){return v.name == name})[0].chinese;
}
function handerPage(listLen,pageSize) {
	pageSize = pageSize || 10;
	return Math.ceil(listLen / pageSize) + 1;
}
/**
 * 按顺序执行函数（通过事件进行执行控制）
 * @event seqFnClose 全部执行完毕
 * @event seqFn0 seqFn1 每当一个执行完成调用才能执行下一个
 * */
function seqCallback(callbackArr, seqIdx) {
	if (callbackArr.length == 0) return;
	seqIdx = seqIdx || 0;
	if (typeof callbackArr[seqIdx] != 'function') return
	callbackArr[seqIdx]();
	if (seqIdx + 1 == callbackArr.length) {
		api.sendEvent({ name: "seqFnClose" })
	} else {
		api.addEventListener({ name: 'seqFn' + seqIdx }, function () {
			seqIdx++;
			seqCallback(callbackArr, seqIdx)
		})
	}
}
//通知
function sendNoticeBar(params){
	api.notification({
		notify: {
			title: params.title || "提示",
			content: params.content || "提醒",
			extra: params.extra || {},
			updateCurrent: true,
		},
		vibrate:[100, 500, 100, 500],
		light:true,
	});
}
//wxPlus 登录
function wxPlusLogin(callback) {
	var wxPlus = api.require('wxPlus');
	wxPlus.isInstalled(function (ret, err) {
		if (ret.installed) {
			wxPlus.auth({
				apiKey: ''
			}, function (ret, err) {
				if (ret.status) {
					var authCode = ret.code; //授权Code
					wxPlus.getToken({
						apiKey: '',
						apiSecret: '',
						code: authCode,
					}, function (ret, err) {
						if (ret.status) {
							var openId = ret.openId;
							var accessToken = ret.accessToken;
							wxPlus.getUserInfo({
								accessToken: accessToken,
								openId: openId,
							}, function (ret, err) {
								if (ret.status) {
									callback(ret)
								} else {
									fox.showToast({ title: "微信用户信息获取失败" })
								}
							});
						} else {
							callback()
							fox.showToast({ title: "微信登录凭证获取失败" })
						}
					});
				} else {
					callback()
					fox.showToast({ title: "登录失败" })
				}
			});
		} else {
			callback()
			fox.showToast({ title: "请先安装微信客户端" })
		}
	});
}
function isToDate(date1,date2){
	var timp = new Date();
	var house = timp.getHours();
	return house >= Number(date1) && house < Number(date2);
}